<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>小球碰撞</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}

			#box {
				width: 700px;
				height: 500px;
				border: 10px solid black;
				margin: 50px auto 0;
				position: relative;
			}

			#ball {
				width: 50px;
				height: 50px;
				background-color: red;
				border-radius: 50%;
				position: absolute;
			}

		</style>
	</head>
	<body>

		<div id="box">
			<div id="ball"></div>
		</div>
		
	</body>
</html>
<script>

	var ball = document.getElementById('ball');

	var left = ball.offsetLeft;
	var a = ball.offsetTop;

	var flagX = true;
	var flagY = true;

	setInterval(moveX, 20);
	setInterval(moveY, 20);
	
	function moveX() {

		if (flagX) {
			left += 5;
		} else {
			left -= 5;
		}

		ball.style.left = left + 'px';
		if (left >= ball.parentNode.clientWidth - ball.offsetWidth || left <= 0) flagX = !flagX; 
		// if (left >= 450) {
		// 	flagX = false;
		// }

		// if (left <= 0) {
		// 	flagX = true;
		// }

	}

	function moveY() {

		if (flagY) {
			a += 2;
		} else {
			a -= 2;
		}

		ball.style.top = a + 'px';
		if (a >= ball.parentNode.clientHeight - ball.offsetHeight || a <= 0) flagY = !flagY; 

	}






</script>




